package com.meilai.project.interceptor;

import com.alibaba.fastjson.JSON;
import com.meilai.project.dto.CommonResult;
import com.meilai.project.mapper.system.UserMapper;
import com.meilai.project.util.JwtTokenUtil;
import com.meilai.project.util.ThreadLocalUserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AppInterceptor implements HandlerInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(AppInterceptor.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserMapper userMapper;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        // 过滤掉不需要加密的登录接口
        if (uri.startsWith("/api/app/behavior_verification")
                || uri.startsWith("/api/app/captcha/image")
                || uri.startsWith("/api/app/company/invite")
                || uri.startsWith("/api/app/login")
                || uri.startsWith("/api/app/extra/get-ver-info")
                || uri.startsWith("/api/app/attachment/upload-anon")) {
            return true;
        }

        String token = request.getHeader(tokenHeader);
        if (token == null) {
            error(response, "请传入token");
            return false;
        }

        String authToken = token.split(" ")[1];

        Long id = Long.parseLong(jwtTokenUtil.getContentFromToken(authToken).toString());

        if (id == 0) {
            error(response, "未找到您的信息");
            return false;
        }

        // 存入本地线程
        ThreadLocalUserUtil.set(userMapper.getUserVOById(id));

        //解析出的用户id加入请求中
        request.setAttribute("tokenUserId", id);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (ThreadLocalUserUtil.get() != null) ThreadLocalUserUtil.remove();
    }

    /**
     * 返回错误信息
     */
    public HttpServletResponse error(HttpServletResponse response, String message) throws Exception {
        //response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSON.toJSON(new CommonResult().validateFailed(message)));
        response.getWriter().flush();
        return response;
    }
}
